// pages/GoodsInfo/GoodsInfo.js
const app=getApp()
const db = wx.cloud.database();
const dbc=wx.cloud.database().command;
const utils = require("../../util/util")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    price: null,
    tag: '',
    discript: '',
    // time:'',
    images:[],
    goodsUser:'',
    goodsUserid:null,
    userI:{},
    status_self:false,
    status_fri:false,
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that=this
    this.setData({
      name: options.name,
      price: options.price,
      tag: options.tag,
      discript: options.discript,
      // time: options.time,
      goodsUser: options.goodsUser,
      goodsUserid: options.goodsUserid,
      goodsUserAva:options.goodsUserAva,
      images: options.images.split(',') ,// 传进的是以逗号分隔的字符串
      userInfo:app.globalData.userInfo
    })
  },
  addFriend(e){
    var that = this;
    wx.cloud.database().collection('chat_record').add({
        data:{
          userA_id:that.data.userI._id,
          userA_nickName:that.data.userI.nickName,
          userA_avatarUrl:that.data.userI.avatar,
          userB_id:that.data.goodsUserid,
          userB_nickName:that.data.goodsUser,
          userB_avatarUrl:that.data.goodsUserAva,
          record:[],
          friend_status:true,
          time: utils.formatTime(new Date())
            },
            success(res) {
                console.log(res)
                wx.showToast({
                  title: '已加至聊天列表',
                })
                wx.navigateTo({
                  url: '/pages/chat/chat'
                })
            }
        })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that=this
    db.collection('Users').where({
      nickName:this.data.userInfo.nickName
    }).get({
      success:function(res){
      that.setData({
        userI:res.data[0]
      })
      }
    })
    if(this.data.goodsUser==app.globalData.userInfo.nickName){
      this.setData({
        status_self:true
      })
    }
    db.collection('chat_record').where(
      dbc.or([
        {
          userA_nickName:that.data.goodsUser,
          userB_nickName:app.globalData.userInfo.nickName,
          friend_status:true
        },
        {
          userB_nickName:that.data.goodsUser,
          userA_nickName:app.globalData.userInfo.nickName,
          friend_status:true
        }
      ])
    ).get().then(
      res=>{
        if(res.data.length!=0){
          that.setData({
            status_fri:true
          })
        }
      }
    )
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})